const { ListNode, List, List2Array } = require('../common')

/* 普通解法 */
var getKthFromEnd = function (head, k) {
  let len = 0
  let p = head
  while (p) {
    len++;
    p = p.next
  }
  p = head
  for (let i = 0; i < len - k; i++) {
    p = p.next
  }
  return p
}

/* 双指针解法 */
getKthFromEnd = function (head, k) {
  let p = q = head
  // 使p前与q k个位置
  for (let i = 0; i < k ; i++) {
    q = q.next
  }
  // p,q同时移动到链表末尾
  while(q){
    p = p.next
    q = q.next
  }
  return p
}
let arr = List2Array(getKthFromEnd(List([1, 2, 3, 4, 5]), 2))
console.log(arr);